package com.kangzhan.controller;

import com.kangzhan.entiy.ReturnEntity;
import com.kangzhan.entiy.User;
import com.kangzhan.services.IUserService;
import com.kangzhan.utils.*;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;



@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    ReturnEntity returnEntity;
    private Logger logger = Logger.getLogger(UserController.class);

    @Resource
    private IUserService userService;

    @Autowired
    RedisUtil redisUtil;

//    @Autowired
//    private StringRedisTemplate template;


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ReturnEntity doLogin(@RequestParam String userCode, @RequestParam String userPassword,
                          HttpServletRequest request, HttpSession session) {
        logger.debug("doLogin====================================");
        //调用service方法，进行用户匹配
        User user = userService.login(userCode, userPassword);
        Long tokenId = System.currentTimeMillis()+RandomUtils.nextInt(10000);
        redisUtil.set(tokenId.toString(),user,3600);

        redisUtil.get(tokenId.toString());
        Map map = new HashMap();
        map.put("token",tokenId);
        map.put("userInfo",user);

        if (null != user) {//登录成功
            return ReturnUtil.success(map);
        } else {
            return ReturnUtil.error("用户名或密码错误");
        }
    }

    @RequestMapping(value = "getUserByPage")
    public ModelAndView getUserList(@RequestParam(value = "userName", required = false) String userName,
                                    @RequestParam(value = "sex", required = false) Integer sex, @RequestParam(value =
            "pageSize", required = false, defaultValue = "10") Integer pageSize, @RequestParam(value = "pageNum",
            required = false, defaultValue = "1") Integer pageNum) {
        PageUtil pageUtil = userService.getUserList(userName, sex, pageSize, pageNum);
        ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("data", pageUtil);
        modelAndView.addObject("userName", userName); modelAndView.setViewName("user/userlist"); return modelAndView;

    }

    @ResponseBody
    @RequestMapping(value = "getUserByPageData")
    public ReturnEntity getUserByPageData(@RequestParam(value = "userName", required = false) String userName,
                                          @RequestParam(value = "sex", required = false) Integer sex, @RequestParam(value =
            "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                          @RequestParam(value = "pageNum",
            required = false, defaultValue = "1") Integer pageNum) {
        PageUtil pageUtil = userService.getUserList(userName, sex, pageSize, pageNum);
        return ReturnUtil.success(pageUtil);

    }


    @RequestMapping(value = "getUserById")
    public void getUserById(@RequestParam("id") Integer id) {
        System.out.println("id:" + id);
    }

    @RequestMapping(value = "getUserById/{id}/{name}")
    public void getUserById(@PathVariable Integer id, @PathVariable String name) {

        System.out.println("id:" + id); System.out.println("name:" + name);
    }

    @ResponseBody
    @RequestMapping(value = "getUserList")
    public String getUserList() {
        return "login";
    }

    @RequestMapping(value = "loginaa")
    public String login() {
        return "login";
    }

    @RequestMapping(value = "delete")
    public void delete(Integer id) {

    }

    @RequestMapping(value = "deleteBatch")
    public void deleteBatch(Integer[] ids) {

    }

    @RequestMapping(value = "update")
    public void update(User user) {

    }

    @RequestMapping(value = "myinsert")
    public String insert() {
        return "user/useradd";
    }


    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public void insert(User user,
                       @RequestParam(value = "a_idPicPath", required = false) MultipartFile[] multipartFiles,
                       HttpServletRequest request) {
        String errorMsg = "";
        String userPicPats = "";
        if (multipartFiles != null && multipartFiles.length > 0) {
            // 多文件上传就是 在正常单文件上传的基础上加一个for循环
            for (MultipartFile multipartFile : multipartFiles) {
                if (multipartFile != null) {
                    //OriginalFilename ：获取用户上传的文件名及后缀
                    String OriginalFilename = multipartFile.getOriginalFilename();
                    //suffix: 获取文件的后缀名
                    String suffix = OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1);
                    //判断文件格式 看自己的业务限制
                    if (FileTypeUtil.imageType(suffix)) {
                        if (multipartFile.getSize() < Constants.imgSize) {
                            //RootPath: 动态获取文件需要保存的根目录
                            String RootPath =
                                    request.getSession().getServletContext().getRealPath(Constants.fileFolder);
                            //fileName: 不能直接用用户上传的文件名，因为会重复，所以使用随机的文件名。
                            // 随机规则为 时间戳+随机数
                            String fileName =
                                    System.currentTimeMillis() + "_" + RandomUtils.nextInt(1000000) + "." + suffix;
                            // realPath：全路径
                            // File.separator :  文件路径分隔符。不要再用 // 或  \
                            // 因为windows和linux文件系统不一样，写死的话会有bug,使用这个方式，会自动判别系统
                            String realPath = RootPath + File.separator + fileName;
                            // 核心代码1 : 新建一个空的文件，用户上传的文件到时候就是它
                            File file = new File(realPath);
                            try {
                                // 核心代码2 : 将接口获取的MultipartFile 转换为 正常的 File
                                multipartFile.transferTo(file);
                                //因为有多个文件，采取使用","拼接的方式，将多个文件地址拼接起来
                                // 更规范的写法应该是使用 json
                                userPicPats += Constants.fileFolder + File.separator + fileName + ",";
                            } catch (IOException e) {
                                FileUtil.delFile(realPath);
                                throw new RuntimeException(e);
                            }
                        } else {
                            errorMsg = "文件过大，请选择小于10M的文件";
                        }
                    } else {
                        errorMsg = "文件类型非法,请选择图片";
                    }
                }
            }
        }
        //文件地址最后会多出来一个”,“,所以使用字符串截取掉最后多余的”,“
        userPicPats = userPicPats.substring(0,userPicPats.length()-1);
        // 核心代码3 :  保存文件的存储路径。注意一定是相对路径。
        user.setUserPicPath(userPicPats);
        userService.save(user);

        System.out.println("aaa");
        System.out.println("aaa");
        System.out.println("aaa");
        System.out.println("aaa");
        System.out.println("aaa");System.out.println("aaa");
        System.out.println("aaa");
        System.out.println("aaa");
        System.out.println("aaa");System.out.println("aaa");


    }


}
